<template>
  <el-dialog class="public-dialog" title="批量导入业绩指标" :modelValue="dialogVisible" align-center width="800" @close="handleClose" :close-on-click-modal="false">
    <p class="text-[14px] leading-[20px] mb-[8px]">第 <span class="font-[600]">1</span> 步：点击下载模版</p>

    <div class="flex">
      <div>
        <label>选择目标类型：</label>
        <el-select v-model="tpl_name" style="width: 200px">
          <el-option label="部门目标" value="部门目标-业绩报表模板.xlsx" />
          <el-option label="个人目标" value="个人目标-业绩报表模板.xlsx" />
        </el-select>
      </div>

      <div class="bg-[#FAFAFA] flex items-center justify-center rounded-[4px] py-[6px] cursor-pointer flex-1" @click="getTemmplate">
        <div class="text-[#3366F1] flex items-center gap-1">
          <div class="dk-iconfont icon-Download"></div>
          下载模板
        </div>
      </div>
    </div>

    <p class="text-[14px] leading-[20px] my-[16px]">第 <span class="font-[600]">2</span> 步：按照模版要求填写</p>
    <p class="text-[14px] leading-[20px] mb-[8px]">第 <span class="font-[600]">3</span> 步：上传填写完成的文件</p>

    <div class="flex mb-[16px]">
      <div>注意：</div>
      <div class="flex-1">
        <p>1. 部门目标跟个人目标需要分开导入</p>
        <p>2. 部门目标中 所属部门 需要严格按照组织架构部门样式填写: 公司-一级部门-二级部门</p>
        <p>3. 部门目标中目标负责人 对应 所属部门填写部门的负责人</p>
      </div>
    </div>

    <el-upload
      ref="upload"
      v-model:file-list="fileList"
      accept=".csv,.xml,.xlsx"
      class="v-import"
      drag
      :data="extraData"
      :action="ossParams.host ? `${ossParams.host}` : ''"
      :limit="1"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
    >
      <div class="text-[#3366F1] flex items-center">
        <div class="dk-iconfont icon-Plus"></div>
        上传文件
      </div>
    </el-upload>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loadings.submit" :disabled="!fileList.length" @click="submit"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from "./api"

import { ElMessage, ElMessageBox, genFileId, ElNotification } from "element-plus"
import { ref } from "vue"
const load = ref(false)

import { uploadSignUrl } from "@/api/public"

const dialogVisible = ref(false)

const props = defineProps({
  oss_key: { type: String, default: "" },
  imporApi: { type: Function, default: () => {} },
})

const tpl_name = ref("个人目标-业绩报表模板.xlsx")
const getTemmplate = async () => {
  const res = await api.getImportTpl({ tpl_name: tpl_name.value })
  window.open(res.data.url, "_blank")
}

let loadings = reactive({})
let ossParams = reactive({
  host: "",
})

const emit = defineEmits(["close", "query"])

const fileList = ref([])
const upload = ref()
const extraData = reactive({})
const uploadPercent = ref(0)
const fileName = ref("")

const handleExceed = (files) => {
  upload.value?.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value?.handleStart(file)
}

const get_suffix = (name) => {
  const pos = name.lastIndexOf(".")
  let suffix = ""
  if (pos != -1) {
    suffix = name.substring(pos)
  }
  return suffix
}

const beforeUpload = async (file) => {
  if (file.size > 1024 * 1024 * 1024) {
    ElMessage.warning("上传文件大小不能超过1G")
    return false
  }
  uploadPercent.value = 0
  try {
    const { policy, accessid, dir, signature } = ossParams || {}
    const name = `${file.name.split(".")[0]}_${new Date().getTime()}`
    const _fileName = name + get_suffix(file.name)
    extraData.key = dir + _fileName
    extraData.policy = policy
    extraData.OSSAccessKeyId = accessid
    extraData.signature = signature
    extraData.oss_url = `${props.oss_key}${_fileName}`
    fileName.value = _fileName
    return true
  } catch (err) {
    fileName.value = ""
    ElMessage.error(err.message)
    return false
  }
}

const handleUploadSuccess = () => {
  if (tpl_name.value == "个人目标-业绩报表模板.xlsx") {
    api.kpiImportPersonal({ oss_url: extraData.oss_url }).then((res) => {
      if (res.data.errors.length) {
        ElMessageBox.confirm(`${res.data.errors.join("<br/>")}`, "提示", {
          confirmButtonText: "确认",
          showCancelButton: false,
          dangerouslyUseHTMLString: true,
          type: "warning",
        }).then(() => {
          handleClose()
          emit("query")
        })
      } else {
        ElMessage({ type: "success", message: `上传成功` })
        handleClose()
        emit("query")
      }
    })
  } else {
    api.kpiImportDept({ oss_url: extraData.oss_url }).then((res) => {
      if (res.data.errors.length) {
        ElMessageBox.confirm(`${res.data.errors.join("<br/>")}`, "提示", {
          confirmButtonText: "确认",
          showCancelButton: false,
          dangerouslyUseHTMLString: true,
          type: "warning",
        }).then(() => {
          handleClose()
          emit("query")
        })
      } else {
        ElMessage({ type: "success", message: `上传成功` })
        handleClose()
        emit("query")
      }
    })
  }
}

const handleUploadError = (err) => {
  fileName.value = ""
  ElMessage.error(`上传失败 ${err.toString()}`)
  uploadPercent.value = 0
}
// 打开弹窗
const open = async () => {
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  loadings.submit = false
  fileList.value = []
}

// 提交
const submit = async () => {
  try {
    loadings.submit = true
    await initUpload()
    upload.value.submit()
    loadings.submit = false
  } catch (error) {
    loadings.submit = false
  }
}
const initUpload = async () => {
  const { data } = await uploadSignUrl({ dir: props.oss_key })
  ossParams = { ...data?.signature }
}

onMounted(() => {
  initUpload()
})

defineExpose({
  open,
  handleClose,
})
</script>

<style lang="scss" scoped>
.v-import {
  :deep(.el-upload-dragger) {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-color: #3366f1;
  }
}
</style>
